import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'
//const baseURL = 'http://localhost:3001/admin/api'
const baseURL = process.env.VUE_APP_API_URL || '/admin/api';
const http = axios.create({
    baseURL
})
http.interceptors.response.use(res => {
    return res;
}, err => {
    const res = err.response;
    ElMessage.error(res.data.message || '请求出错');
    if (res.status === 401) {
        router.push('/login');
    }
    return Promise.reject(err);
})


http.interceptors.request.use(config => {
    const token = localStorage.token;
    const Authorization = 'Bearer ' + token;
    if (token) { config.headers.Authorization = Authorization };
    return config;
}, err => {
    return Promise.reject(err);
})

function getToken() {
    return {
        Authorization: Authorization || ''
    }
}




function getData(url, payload, tip) {
    return http.get(url, payload)
        .then(res => {
            tip && ElMessage.success(tip);
            return res;
        })
        .catch(err => {
            return err;
        })
}

function postData(url, payLoad, tip) {
    return http.post(url, payLoad)
        .then(res => {
            tip && ElMessage.success(tip);
            return res;
        })
        .catch(err => {
            return err;
        })
}

function putData(url, payLoad, tip) {
    return http.put(url, payLoad)
        .then(res => {
            tip && ElMessage.success(tip);
            return res;
        })
        .catch(err => {
            return err;
        })
}
function deleteData(url, tip) {
    return http.delete(url)
        .then(res => {
            if (res.data.success) {
                tip && ElMessage.success(tip);
                return res;
            }
            return res;
        })
        .catch(err => {
            return err;
        })
}
export {
    baseURL, http, postData, getData, putData, deleteData, getToken
}